package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
//        处理业务异常(地址簿、购物车数据为空)
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        Long userId = BaseContext.getCurrentId();
        ShoppingCart build = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(build);
        if (shoppingCarts == null || shoppingCarts.size() == 0)
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
//    向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(userId);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setOrderTime(LocalDateTime.now());
        orders.setAddress(addressBook.address());
        orderMapper.insert(orders);
//    向订单明细表插入n条数据
        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);
        }
        orderDetailMapper.insertBatch(list);

//    清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(userId);
//    封装VO返回结果
        OrderSubmitVO submitVO = OrderSubmitVO.builder().id(orders.getId()).orderTime(orders.getOrderTime()).orderNumber(orders.getNumber()).orderAmount(orders.getAmount()).build();
        return submitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        String number = ordersPaymentDTO.getOrderNumber();
        Orders ordersDB = orderMapper.getByNumber(number);


//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改

        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付

        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单


        //发现没有将支付时间 check_out属性赋值，所以在这里更新

        LocalDateTime check_out_time = LocalDateTime.now();
        Orders orders = Orders.builder().number(number).checkoutTime(check_out_time).payStatus(OrderPaidStatus).status(OrderStatus).build();


//        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, number);
        orderMapper.updateByNumber(orders);
        Map map = new HashMap();
        map.put("type", 1);//1表示来单提醒  2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + number);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
//        通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type", 1);//1表示来单提醒  2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号:" + outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    public OrderVO getOrderAndDetailById(Long id) {
//        查询该订单
        Orders orders = orderMapper.getById(id);
//        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
//        String address = addressBook.address();
//        orders.setAddress(address);
//        查询订单相关的菜品信息
        List<OrderDetail> orderDetailList = orderDetailMapper.selectBatchByOrderID(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
//        封装返回数据
        return orderVO;
    }

    @Override
    public PageResult pageQuery(OrdersPageQueryDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Long userId = BaseContext.getCurrentId();

        dto.setUserId(userId);

        Page<Orders> page = orderMapper.pageQuery(dto);

        List<OrderVO> orderVOList = new ArrayList<>();
        if (page != null && page.size() > 0) {
            for (Orders order : page) {
                List<OrderDetail> orderDetailList = orderDetailMapper.selectBatchByOrderID(order.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                orderVOList.add(orderVO);

            }
        }


        return new PageResult(page.getTotal(), orderVOList);
    }

    @Override
    public void userCancelById(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        Integer status = ordersDB.getStatus();
        if (status > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        if (status.equals(Orders.TO_BE_CONFIRMED)) {
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orders.setStatus(Orders.CANCELLED);

        orderMapper.update(orders);
    }

    @Override
    public void repetition(Long id) {
//        查出原本的订单信息及其包含的菜品
        List<OrderDetail> orderDetailList = orderDetailMapper.selectBatchByOrderID(id);
//
//        orders.setOrderTime(LocalDateTime.now());
//        orders.setStatus(Orders.PENDING_PAYMENT);
//        orderMapper.insert(orders);
//        Long newId = orders.getId();
        Long currentId = BaseContext.getCurrentId();

        List<ShoppingCart> cartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(currentId);
            cartList.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(cartList);


    }

    public PageResult conditionSearch(OrdersPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        List<OrderVO> ordersVoList = new ArrayList<>();
        Page<Orders> ordersList = orderMapper.conditionSearch(pageQueryDTO);

        if (ordersList != null && ordersList.getTotal() > 0) {
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                List<OrderDetail> orderDetailList = orderDetailMapper.selectBatchByOrderID(orders.getId());
                orderVO.setOrderDishes(DishesToStr(orderDetailList));
//                orderVO.setOrderDishes(orderDetailList.toString());
                ordersVoList.add(orderVO);
            }
        }

        return new PageResult(ordersList.getTotal(), ordersVoList);
    }

    private String DishesToStr(List<OrderDetail> orderDetailList) {
        List<String> dishes = new ArrayList<>();
        for (OrderDetail detail : orderDetailList) {
            dishes.add(detail.getName() + "*" + detail.getNumber() + ";");
        }

        return String.join("", dishes);
    }

    public OrderStatisticsVO statistics() {
        OrderStatisticsVO vo = new OrderStatisticsVO();
        Integer toBeConfirmed = orderMapper.getOneStatusAmount(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.getOneStatusAmount(Orders.CONFIRMED);
        Integer deliverInProcess = orderMapper.getOneStatusAmount(Orders.DELIVERY_IN_PROGRESS);
        vo.setConfirmed(confirmed);
        vo.setToBeConfirmed(toBeConfirmed);
        vo.setDeliveryInProgress(deliverInProcess);

        return vo;
    }

    @Override
    public void acceptOrders(OrdersConfirmDTO dto) {
//        改变订单状态
        Orders orders = Orders.builder().id(dto.getId()).status(Orders.CONFIRMED).build();
        orderMapper.update(orders);
    }

    @Override
    @Transactional
    public void rejectionOrders(OrdersRejectionDTO dto) {
//        只有待接单状态可以取消订单
        Orders orders = orderMapper.getById(dto.getId());
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //      已支付则退款
        if (orders.getStatus().equals(Orders.PAID)) {
            orders.setPayStatus(Orders.REFUND);
        }
//      拒单原因
        orders.setCancelReason(dto.getRejectionReason());

//        改变订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);


    }

    @Override

    public void adminCancelById(OrdersCancelDTO cancelDTO) {
        Orders ordersDB = orderMapper.getById(cancelDTO.getId());
//        只有待派送且存在的订单可以有商家取消
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
//        退款
        if (ordersDB.getPayStatus().equals(Orders.PAID)) {
            orders.setPayStatus(Orders.REFUND);
        }

//        取消原因和时间
        orders.setCancelReason(cancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
//        修改状态
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        Orders ordersDB = orderMapper.getById(id);
//        只有已接单且存在的订单可以派送
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(id);
//        修改状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders ordersDB = orderMapper.getById(id);
//        只有已接单且存在的订单可以派送
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(id);
//        修改状态
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB==null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);

        Map map = new HashMap();
        map.put("type", 2);//1表示来单提醒  2表示客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号: " + ordersDB.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

}
